package api

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strings"
	. "xm_shop/database"
	. "xm_shop/models"
)

type DefaultController struct{}

// 商城首页信息
func (d DefaultController) Index(context *gin.Context) {
	// 获取顶部导航
	var topNavList []Nav
	// 获取网站轮播图
	var focusList []Focus
	// 获取分类
	var goodsCateList []GoodsCate
	// 获取中间导航
	var middleNavList []Nav

	// redis缓存中间导航栏
	if flag := CacheDB.Get("middleNavList", &middleNavList); !flag {
		DB.Where("status = ? AND position = ?", 1, 2).Find(&middleNavList)
		CacheDB.Set("middleNavList", middleNavList, 60*60)
	}
	for i := 0; i < len(middleNavList); i++ {
		// 中文转换
		relation := strings.ReplaceAll(middleNavList[i].Relation, "，", ",") // 关联商品 11,12,13,14
		// 转切片
		relationIds := strings.Split(relation, ",")
		// 检索数据
		var goodsList []Goods
		DB.Where("id in ?", relationIds).Select("id,title,goods_img,price").Find(&goodsList)
		// 填充
		middleNavList[i].GoodsItems = goodsList
	}

	// 获取指定分类的商品redis
	var goodsList []Goods
	if flag := CacheDB.Get("goodsList", &goodsList); !flag {
		goodsList = GetGoodsByCategory(1, "best", 8)
		CacheDB.Set("goodsList", goodsList, 60*60)
	}
	// 获取顶级分类和次级分类redis
	if flag := CacheDB.Get("goodsCateList", &goodsCateList); !flag {
		DB.Where("pid = ? AND status = ?", 0, 1).Order("sort desc").Preload("GoodsCateItems", func(DB *gorm.DB) *gorm.DB {
			return DB.Where("goods_cate.status = ?", 1).Order("goods_cate.sort DESC")
		}).Find(&goodsCateList)
		CacheDB.Set("goodsCateList", goodsCateList, 60*60) // 打入缓存
	}
	// 顶部导航栏redis
	if flag := CacheDB.Get("topNavList", &topNavList); !flag { // 如果redis中没有, 就取mysql
		DB.Where("status = ? AND position = ?", 1, 1).Find(&topNavList)
		// 打入redis作备份
		CacheDB.Set("topNavList", topNavList, 60*60)
	}
	// 轮播图也采用redis
	if flag := CacheDB.Get("focusList", &focusList); !flag { // 如果redis中不存在
		DB.Where("status = ? AND focus_type = ?", 1, 1).Find(&focusList) // 检索数据库
		CacheDB.Set("focusList", focusList, 60*60)                       // 打入缓存
	}
	// 获取cookie里面的用户数据
	var user User
	Cookie.Get(context, "userInfo", &user)

	context.JSON(http.StatusOK, gin.H{
		"topNavList":    topNavList,
		"focusList":     focusList,
		"goodsCateList": goodsCateList,
		"middleNavList": middleNavList,
		"goodsList":     goodsList,
		"user":          user,
	})
}
